package com.binguo.common.sms;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

public class HttpClients {

	public static String doPost(String url, Object params) {
		HttpParams httpParams = new BasicHttpParams();
		//		HttpConnectionParams.setConnectionTimeout(httpParams, 15000);
		//		HttpConnectionParams.setSoTimeout(httpParams, 15000);
		HttpClient client = new DefaultHttpClient(httpParams);

		HttpPost request = new HttpPost(url);
		String strResult = "";
		if (params != null) {
			String requestData = JacksonUtil.bean2Json(params);
			StringEntity entity = new StringEntity(requestData, "utf-8");
			request.setEntity(entity);
		}
		try {
			request.addHeader("charset", "utf-8");
			request.addHeader("Content-Type", "application/json");
			HttpResponse response = null;
			response = client.execute(request);

			HttpEntity httpEntity = response.getEntity();
			BufferedReader reader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), "utf-8"));
			String temp = null;
			while ((temp = reader.readLine()) != null) {
				strResult += temp;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strResult;
	}

	public static String doFormPost(String url, List<NameValuePair> formparams) throws ClientProtocolException, IOException {
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(url);

		UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
		uefEntity.setContentType("application/x-www-form-urlencoded");
		uefEntity.setContentEncoding("utf-8");
		httppost.setEntity(uefEntity);
		HttpResponse response = httpClient.execute(httppost);
		HttpEntity entity = response.getEntity();
		String res = EntityUtils.toString(entity, "UTF-8");
		return res;
	}

}
